//
//  LWKTabBarController.swift
//  ljy_demo
//
//  Created by xiandao on 2025/9/4.
//

import UIKit
import CoreLocation

class LWKTabBarController: UITabBarController {
    var tabCenterClickCall: (() -> ())?
    
    open var curTabBar: LWKRootTabBar? {
        let bar = tabBar as? LWKRootTabBar
        bar?.delegate = self
        return bar
    }
    
    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        self.tabbar.isHidden = true
        if item.title == nil {
            print("titile 为空")
        }
    }
    
    private lazy var tabbar: LWKRootTabBar = {
        let tab = LWKRootTabBar()
        if isIphoneX {
            tab.layer.cornerRadius = 40
        } else {
            tab.layer.cornerRadius = 20
        }
        tab.addDelegate = self
        // 解决tabbar显示分割线的问题
        tab.backgroundImage = UIImage()
        tab.shadowImage = UIImage()
        return tab
    }()
    lazy var locationManager: CLLocationManager = {
        let locationManager: CLLocationManager = CLLocationManager.init()
        locationManager.delegate = self
        return locationManager
    }()
    
    private var config = LWKRootTabBarConfig()

    private var tabBarModels = [LWKRootTabBarModel]()
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        UITableView.appearance().tableFooterView = UIView()
        UITableView.appearance().backgroundColor = UIColor.hex(hexString: "#f3f3f5")
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    init(config: LWKRootTabBarConfig, tabBars: [LWKRootTabBarModel]) {
        self.config = config
        self.tabBarModels = tabBars
        self.config.viewControllerCount = tabBarModels.count
        super.init(nibName: nil, bundle: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.setValue(tabbar, forKey: "tabBar")
        self.setConntrollers()
        tabbar.config(config)
        // 淡化 tabBar 黑线
        self.tabBar.shadowImage = UIColor.creatImageWithColor(color: config.tabBarShadowColor!,size: CGSize(width: screenWidth, height: 0.5))
        self.tabbar.isHidden = true
        self.tabbar.backgroundImage = UIImage()
        self.tabbar.shadowImage = tabBarShadowImage()
        if #available(iOS 14.0, *) {
            checkLocationPermission(status: self.locationManager.authorizationStatus)
        } else {
            // Fallback on earlier versions
            checkLocationPermission(status:CLLocationManager.authorizationStatus())
        }
        
        self.view.addSubview(locationPermissionAlertView)
        locationPermissionAlertView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    private lazy var locationPermissionAlertView : LWKLocationAlertView = {
        let view = LWKLocationAlertView()
        view.isHidden = true
        view.delegate = self
        return view
    }()
    
    func setConntrollers() {
        if self.config.viewControllerCount%2 != 0 { // 不为双数，只能为默认类型， 中心圆设置不起效
            config.tabBarStyle = .center
        }
        
        for i in 0 ..< self.tabBarModels.count {
            let model = self.tabBarModels[i]
            //创建导航控制器
            let nav = LWKNaviController.init(rootViewController: model.controller)
            nav.isNavigationBarHidden = true
            /// 配置 导航栏
            
            //1.创建tabbarItem
            let barItem = UITabBarItem.init(title: model.title, image: UIImage(named: model.imageNormal)?.withRenderingMode(.alwaysOriginal), selectedImage: UIImage(named: model.imageSelected)?.withRenderingMode(.alwaysOriginal))
            
            //2.更改字体颜色
            if #available(iOS 13.0, *) {
                tabbar.tintColor = config.titleColorSelected
                tabbar.unselectedItemTintColor = config.titleColorNormal
            } else {
                barItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor : config.titleColorNormal!], for: .normal)
                barItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor : config.titleColorSelected!], for: .selected)
            }
            
            //设置标题
           // model.controller.title = model.title
            
            //设置根控制器
//            model.controller.tabBarItem = barItem
            
            //添加到当前控制器
            addChild(nav)
        }
    }
    
    func tabBarShadowImage() -> UIImage? {

        UIGraphicsBeginImageContextWithOptions(CGSize(width: kScreen_width, height: 0.5), false, 0)

        let path = UIBezierPath.init(rect: CGRect.init(x: 0, y: 0, width: kScreen_width, height: 0.5))

        UIColor.clear.setFill()// 自定义TabBar分割线颜色

        path.fill()

        let image = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        return image
    }
}

extension LWKTabBarController: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        checkLocationPermission(status: status)
    }
    
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        if #available(iOS 14.0, *) {
            checkLocationPermission(status: manager.authorizationStatus)
        } else {
            // Fallback on earlier versions
        }
    }

    // 检测权限状态
    func checkLocationPermission(status: CLAuthorizationStatus) {
        switch status {
        case .notDetermined:
            print("🔹 用户尚未选择是否允许定位 - \(#function)")
        case .restricted:
            print("🔒 定位权限被限制（家长控制或 MDM 管理）- \(#function)")
            self.locationPermissionAlertView.isHidden = false
        case .denied:
            print("🚫 用户拒绝了 App 的定位权限 - \(#function)")
            self.locationPermissionAlertView.isHidden = false
        case .authorizedWhenInUse:
            print("✅ 用户允许 App 在前台使用定位 - \(#function)")
        case .authorizedAlways:
            print("✅ 用户允许 App 在前台 & 后台使用定位 - \(#function)")
        @unknown default:
            print("⚠️ 未知的定位权限状态 - \(#function)")
            self.locationPermissionAlertView.isHidden = false
        }
    }
}


extension LWKTabBarController: LWKRootTabBarDelegate {
    /// 中间特殊按钮执行方法
    func addClick() {
        if config.isAnimation { // 有动画，延迟0.6秒
            self.perform(#selector(centerClick), with: nil, afterDelay: 0.35)
        } else {
            centerClick()
        }
    }
    
    @objc func centerClick() {
        print("center click")
        if tabCenterClickCall != nil {
            tabCenterClickCall!()
        }
    }
}

extension LWKTabBarController: LWKLocationAlertViewDelegate {
    // 定位权限弹窗关闭
    func locationViewClose() {
        self.locationPermissionAlertView.isHidden = true
    }
}

//extension LWKAccountSecurityViewController {
//    public var curTabBarController: LWKTabBarController? {
//        return tabBarController as? LWKTabBarController
//    }
//}

extension UIViewController {
    internal var bottomTabBarController: LWKTabBarController? {
        return tabBarController as? LWKTabBarController
    }
}
